<?php

namespace app\command;

use app\common\facade\Arr;
use app\common\facade\Help;
use app\common\services\WechatTemplateService;
use Carbon\Carbon;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\Config;
use library\tools\Data;


class PlatformMarketCommand extends BasicCommand
{

    protected $name = 'stat:platform-market';

    protected $desc = '平台二手统计程序';

    private $_everyTime = 100;

     /**
     * @param Input $input
     * @param Output $output
     * @return int|null|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function execute(Input $input, Output $output)
    {

        $timeRange = $this->__getTimeRange();
        $this->__handleStatistic($this->_everyTime, $timeRange);
    }


    /**
     * 处理一个代理商的数据
     * @param $length
     * @param $timeRange
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    private function __handleStatistic($length, $timeRange)
    {

        $result = [
            'total'       => 0,
        ];
        $subResult = [];
        //门店的接单数据统计
        $offset = ['offset' => 0, 'length' => $length];
        while (true) {
            $MarketList = $this->__getTakeMarket($offset, $timeRange);
            if (!$MarketList) {
                unset($offset);
                break;
            }
            foreach ($MarketList as $order) {
                //总平台
                $result['total'] += Arr::get($order, 'total', 0);
            }
            $offset['offset'] += $offset['length'];
        }
        Db::startTrans();
        $dayData = [
            'for_time'          => Arr::get($timeRange, 'day'),
            'total'             => Arr::get($result, 'total'),
            'type'              => 1,
            'for_time_start'    => Arr::get($timeRange, 'dayTimeStart'),
            'for_time_end'      => Arr::get($timeRange, 'dayTimeEnd'),
            'created_at'        => Carbon::now()->getTimestamp(),
            'updated_at'        => Carbon::now()->getTimestamp(),
        ];
        $exitId = $this->__checkStatisticExit($dayData);

        if ($exitId!='-1') {
            $dayData['id'] = $exitId;
        }

        //门店日结算统计表
        $handleDay=Data::save("platform_market_stat",$dayData);

        //门店月度结算统计
        $handleMonth = $this->__handleBusinessCycle($timeRange, $result);

        if ($handleDay && $handleMonth) {
            echo "handle success";
            Db::commit();
        } else {
            echo "handle error";
            Db::rollback();
        }

    }

    /**
     * 门店周期报表处理
     * @param $store
     * @param $timeRange
     * @param $result
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    private function __handleBusinessCycle($timeRange, $result)
    {
        $businessStatMonth = Db::name('platform_market_stat')
            ->where('type', 2)
            ->where('for_time_start', Arr::get($timeRange, 'monthStart'))
            ->where('for_time_end', Arr::get($timeRange, 'monthEnd'))
            ->find();

        if ($businessStatMonth) {
            $success = Db::name('platform_market_stat')
                ->where('id', Arr::get($businessStatMonth, 'id'))
                ->update([
                    'total'       => Db::raw('total + ' . Arr::get($result, 'total', 0)),
                    'updated_at'        => Carbon::now()->getTimestamp(),
                ]);
        } else {
            $success = Db::name('platform_market_stat')->insert([
                'for_time'          => Arr::get($timeRange, 'monthStart'),
                'total'             => Arr::get($result, 'total'),
                'for_time_start'    => Arr::get($timeRange, 'monthStart'),
                'for_time_end'      => Arr::get($timeRange, 'monthEnd'),
                'type'              => 2,
                'created_at'        => Carbon::now()->getTimestamp(),
                'updated_at'        => Carbon::now()->getTimestamp(),
            ]);
        }
        return $success;
    }

   


     /**
     * 检查统计是否存在
     * @param $data
     * @return bool
     */
    private function __checkStatisticExit($data)
    {
        $exitId = Db::name('platform_market_stat')
            ->where('type', Arr::get($data, 'type'))
            ->where('for_time', Arr::get($data, 'for_time'))
            ->where('for_time_start', Arr::get($data, 'for_time_start'))
            ->where('for_time_end', Arr::get($data, 'for_time_end'))
            ->value('id');
        return $exitId ?: -1;
    }

    /**
     * 获取代理商数据
     * @param $store
     * @param $offset
     * @param $timeRange
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function __getTakeMarket($offset, $timeRange)
    {   
        $orderList = Db::name('agency_market_stat')
            ->where('for_time_start', '=', Arr::get($timeRange, 'dayTimeStart'))
            ->where('type', '=', 1)
            ->where('for_time_end', '=', Arr::get($timeRange, 'dayTimeEnd'))
            ->limit(Arr::get($offset, 'offset'), Arr::get($offset, 'length'))
            ->order('created_at ASC')
            ->select();
        return $orderList ?: [];
    }


    /**
     * 获取所有的代理商
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function __getAgencyList()
    {
        $agencyList = Db::name('system_agent_user')
            ->where('pid', 0)
            ->where('status', 1)
            ->field('id,provinces_id,city_id')
            ->select() ?: [];
        return $agencyList;
    }



     /**
     * 获取统计时间节点
     * @return array
     */
    private function __getTimeRange()
    {
        return [
            'dayTimeStart'      => Carbon::yesterday()->getTimestamp(),
            'dayTimeEnd'        => Carbon::yesterday()->addHours(23)->addMinutes(59)->addSeconds(59)->getTimestamp(),
            'day'               => Carbon::yesterday()->getTimestamp(),
            'monthStart'        => Carbon::yesterday()->startOfMonth()->getTimestamp(),//一个月的第一天
            'monthEnd'          => Carbon::yesterday()->lastOfMonth()->addHours(23)->addMinutes(59)->addSeconds(59)->getTimestamp()//
        ];
    }





}
